package com.ruoyi.web.controller.eduManage;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.eduManage.domain.dto.DailyStatisticsMailDTO;
import com.ruoyi.eduManage.service.IMailDataService;
import com.ruoyi.eduManage.utils.MailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 每日统计邮件测试控制器
 * 
 * @author ruoyi
 */
@Api(tags = "每日统计邮件管理")
@RestController
@RequestMapping("/eduManage/mail/statistics")
public class DailyStatisticsMailController extends BaseController {
    
    @Autowired
    private IMailDataService mailDataService;
    
    @Autowired
    private MailUtils mailUtils;
    
    /**
     * 获取所有教师的每日统计数据（用于预览）
     */
    @ApiOperation("获取所有教师的每日统计数据")
    // @PreAuthorize("@ss.hasPermi('eduManage:mail:list')")  // 临时注释用于测试
    @GetMapping("/preview")
    public AjaxResult previewStatistics(
            @ApiParam("开始日期") @RequestParam String startDate,
            @ApiParam("结束日期") @RequestParam String endDate,
            @ApiParam("预期天数") @RequestParam(defaultValue = "1") Integer expectedDays) {
        try {
            List<DailyStatisticsMailDTO> statisticsList = mailDataService.getAllTeachersDailyStatistics(
                startDate, endDate, expectedDays);
            return AjaxResult.success(statisticsList);
        } catch (Exception e) {
            logger.error("获取统计数据失败: {}", e.getMessage());
            return AjaxResult.error("获取统计数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取指定教师的每日统计数据
     */
    @ApiOperation("获取指定教师的每日统计数据")
    // @PreAuthorize("@ss.hasPermi('eduManage:mail:list')")  // 临时注释用于测试
    @GetMapping("/teacher/{teacherNo}")
    public AjaxResult getTeacherStatistics(
            @ApiParam("教师编号") @PathVariable String teacherNo,
            @ApiParam("开始日期") @RequestParam String startDate,
            @ApiParam("结束日期") @RequestParam String endDate,
            @ApiParam("预期天数") @RequestParam(defaultValue = "1") Integer expectedDays) {
        try {
            DailyStatisticsMailDTO statistics = mailDataService.getTeacherDailyStatistics(
                teacherNo, startDate, endDate, expectedDays);
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("获取教师统计数据失败: {}", e.getMessage());
            return AjaxResult.error("获取教师统计数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 发送测试邮件给指定教师
     */
    @ApiOperation("发送测试邮件给指定教师")
    @Log(title = "测试邮件", businessType = BusinessType.OTHER)
    // @PreAuthorize("@ss.hasPermi('eduManage:mail:send')")  // 临时注释用于测试
    @PostMapping("/test/{teacherNo}")
    public AjaxResult sendTestMail(
            @ApiParam("教师编号") @PathVariable String teacherNo,
            @ApiParam("开始日期") @RequestParam String startDate,
            @ApiParam("结束日期") @RequestParam String endDate,
            @ApiParam("预期天数") @RequestParam(defaultValue = "1") Integer expectedDays) {
        try {
            // 获取教师统计数据
            DailyStatisticsMailDTO statistics = mailDataService.getTeacherDailyStatistics(
                teacherNo, startDate, endDate, expectedDays);
            
            if (statistics == null) {
                return AjaxResult.error("未找到教师统计数据");
            }
            
            if (statistics.getTeacherEmail() == null || statistics.getTeacherEmail().trim().isEmpty()) {
                return AjaxResult.error("教师未配置邮箱地址");
            }
            
            // 准备模板变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("teacherName", statistics.getTeacherName());
            variables.put("startDate", statistics.getStartDate());
            variables.put("endDate", statistics.getEndDate());
            variables.put("classDataList", statistics.getClassDataList());
            
            // 发送邮件
            String subject = String.format("测试邮件 - 学生打卡统计报告 - %s至%s", startDate, endDate);
            boolean success = mailUtils.sendTemplateMailWithConfig(
                statistics.getTeacherEmail(),
                subject,
                "daily-statistics-simple",
                variables,
                false
            );
            
            if (success) {
                return AjaxResult.success("测试邮件发送成功");
            } else {
                return AjaxResult.error("测试邮件发送失败");
            }
        } catch (Exception e) {
            logger.error("发送测试邮件失败: {}", e.getMessage());
            return AjaxResult.error("发送测试邮件失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取邮件模板预览
     */
    @ApiOperation("获取邮件模板预览")
    // @PreAuthorize("@ss.hasPermi('eduManage:mail:list')")  // 临时注释用于测试
    @GetMapping("/template/preview/{teacherNo}")
    public AjaxResult previewTemplate(
            @ApiParam("教师编号") @PathVariable String teacherNo,
            @ApiParam("开始日期") @RequestParam String startDate,
            @ApiParam("结束日期") @RequestParam String endDate,
            @ApiParam("预期天数") @RequestParam(defaultValue = "1") Integer expectedDays) {
        try {
            // 获取教师统计数据
            DailyStatisticsMailDTO statistics = mailDataService.getTeacherDailyStatistics(
                teacherNo, startDate, endDate, expectedDays);
            
            if (statistics == null) {
                return AjaxResult.error("未找到教师统计数据");
            }
            
            return AjaxResult.success("模板数据获取成功", statistics);
        } catch (Exception e) {
            logger.error("获取模板预览失败: {}", e.getMessage());
            return AjaxResult.error("获取模板预览失败: " + e.getMessage());
        }
    }
}